import Vue from 'vue';
import VueRouter from 'vue-router';
import { Toast } from 'vant';

import routes from './routes';
import auth from '../utils/auth';

Vue.use(VueRouter);

// 路由配置
const router = new VueRouter({
  base: __dirname,
  routes: routes,
  caseSensitive: true
});

router.beforeEach((to, from, next) => {
  Toast.loading({
    mask: true,
    message: '加载中...'
  });

  auth.getToken().then(function(token) {
    if (token !== null && to.name === 'login') {
      next({ name: 'homeIndex' });
    } else if (token !== null && to.name !== 'login') {
      next();
    } else if (token !== null && to.name !== 'login') {
      next({ name: 'login' });
    } else if (['login', 'into', 'forgetPassword', 'register', 'homeIndex', 'notice', 'products'].indexOf(to.name) !== -1) {
      next();
    } else {
      next({ name: 'login' });
    }
  });
});

router.afterEach(() => {
  Toast.clear();
  window.scrollTo(0, 0);
});

export default router;
